import apis from '@/apis'
import axios from '@/apis/request'
import { ref } from 'vue'
import { validPhoneNumber } from '@/utils/validator'

const useSms = () => {
	let timer = null
	const waitSecond = ref(0)

	function sendSmsCode(mobile, imgVerifyCode, second = 60) {
		if (!validPhoneNumber.test(mobile)) {
			uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
			return
		}
		if (!imgVerifyCode) {
			uni.showToast({ title: '请输入图形验证码', icon: 'none' })
			return
		}
		if (waitSecond.value > 0) {
			uni.showToast({ title: '请稍后再试', icon: 'none' })
			return
		}
		console.log('mobile', mobile)
		console.log('imgVerifyCode', imgVerifyCode)
		console.log('url', apis.register.registerSendSms)
		axios
			.post(apis.register.registerSendSms, {
				mobile,
				verifyCode: imgVerifyCode
			})
			.then(() => {
				waitSecond.value = second
				timer = setInterval(() => {
					if (waitSecond.value < 1) {
						clearInterval(timer)
						timer = null
					} else {
						waitSecond.value--
					}
				}, 1000)
			})
	}

	const verifyCodeUrl = ref('')
	function getVerifyCodeUrl() {
		verifyCodeUrl.value = import.meta.env.VITE_API_URL + apis.common.getVerifyCode + '?t=' + new Date().getTime()
	}

	return {
		waitSecond,
		sendSmsCode,
		verifyCodeUrl,
		getVerifyCodeUrl
	}
}

export default useSms
